//定位显示
var arrayLi = [];
var arrayLiInd = 0;
var isFtpTest = false;
$(document).ready(function() {
	
	
		/* 系统树 */
		$('#system_selection').window({
			width:310,
			height:355,
			modal:true,
			minimizable:false,
			maximizable:false,
			collapsible:false,
			onClose: function () {
				$("#tt").html("");
			}
		});
		$('#system_selection').window('close');  //关闭窗口
		
		$('input[name=qx]').attr('checked',true);
	
      // Initialize Smart Wizard
  		$('#wizard').smartWizard({
  		  // Properties
  		    selected: 0,  // Selected Step, 0 = first step   
  		    keyNavigation: false, // Enable/Disable key navigation(left and right keys are used if enabled)
  		    enableAllSteps: false,  // Enable/Disable all steps on first load
  		    transitionEffect: 'fade', // Effect on navigation, none/fade/slide/slideleft
  		    contentURL:null, // specifying content url enables ajax content loading
  		    contentCache:true, // cache step contents, if false content is fetched always from ajax url
  		    cycleSteps: false, // cycle step navigation
  		    enableFinishButton: false, // makes finish button enabled always
  		    errorSteps:[],    // array of step numbers to highlighting as error steps
  		    labelNext:'下一步', // label for Next button
  		    labelPrevious:'上一步', // label for Previous button
  		    labelFinish:'提交',  // label for Finish button        
  		  // Events
  		    onLeaveStep: onLeaveStepCallBack, // triggers when leaving a step
  		    onShowStep: onShowStepCallBack,  // triggers when showing a step
  		    onFinish: onFinishCallBack  // triggers when Finish button is clicked
  		 });
  		
  		 
  		
  		$('#comboxFieldName').combobox({
			url: BASE_URL_FIELD_SEARCH + '/findAllOfCurrentUserCanManage' + '?v=' + Math.random(),
			valueField: 'id',
		    textField: 'name',
		    editable:false,
		    method:'get',
		    loadFilter: function(data){
		    	return data.content;
		    },
		    onLoadSuccess:function(){
		    	var FieldName = $('#comboxFieldName').combobox('getData');
		    	$("#comboxFieldName").combobox('setValue',FieldName[0].id);
		    },	
		    onSelect: function(record){
		    	comboxSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: record.id},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findByFieldOfCurrentUserCanManage' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
        		    loadFilter: function(data){
        		    	return data.content;
        		    }
                }).load();
		    },
		    onChange: function(newValue,oldValue){
		    	comboxSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: newValue},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findByFieldOfCurrentUserCanManage' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
        		    loadFilter: function(data){
        		    	return data.content;
        		    },
        		    onLoadSuccess : function(){
        		    	var SystemName = $('#comboxSystemName').combobox('getData');
        				$("#comboxSystemName").combobox('setValue',SystemName[0].id);
        		    }
                }).load();
		    }
		    
		});
		
		
		var comboxSystemName = $('#comboxSystemName').combobox({
            disabled: true,
            valueField: 'id',
            textField: 'name',
            editable:false
        });
		
		
		$('#comboxIsPublic').combobox({
			url: BASE_URL_DATA_DICTIONARY_VALUE_SEARCH +'/findByTypeCode?typeCode='+DDTC_IS_PUBLIC + '&v=' + Math.random(),
			valueField: 'valueCode',
		    textField: 'valueName',
		    editable:false,
		    method:'get',
		    loadFilter:function(data){
		    	return data;
		    },
		    onLoadSuccess:function(){
		    	var isPublic = $('#comboxIsPublic').combobox('getData');
		    	$("#comboxIsPublic").combobox('setValue',isPublic[0].valueCode);
		    	
		    	var chooseVal = $("#comboxIsPublic").combobox('getValue');
		    	if(chooseVal=="0"){
		    		$("#li_visible").css("display","block");
		    	}else{
		    		$("#li_visible").css("display","none");
		    	}
		    	
		    },
		    onSelect: function(record){
		    	var chooseVal = $("#comboxIsPublic").combobox('getValue');
		    	if(chooseVal=="0"){
		    		$("#li_visible").css("display","block");
		    	}else{
		    		$("#li_visible").css("display","none");
		    	}
		    }
		});
		
		
		
		$('#comboxExecutionCycleTime').combobox({
			url: BASE_URL_DATA_DICTIONARY_VALUE_SEARCH +'/findByTypeCode?typeCode='+DDTC_KETTLE_JOB_SCHEDULE_CYCLE_UNIT + '&v=' + Math.random(),
			valueField: 'valueCode',
		    textField: 'valueName',
		    editable:false,
		    method:'get',
		    loadFilter:function(data){
		    	return data;
		    },
		    onChange:function(e){
		    	var chooseVal = $("#comboxExecutionCycleTime").combobox('getValue');
				var cycleNum = $('#txtExecutionCycleNumber').val();
				if(chooseVal == "5" && cycleNum == "1")
				{
					$(".daySel, .txtEvery, .text_tips, #end_time_li").show();
				}else if(chooseVal == "1")
				{
					$(".txtEvery, .daySel, .text_tips, #end_time_li").hide();
				}else
				{
					$(".txtEvery, .text_tips, #end_time_li").show();
					$(".daySel").hide();
				}
		    },
		    onLoadSuccess:function(){
		    	var cycleTimeData = $('#comboxExecutionCycleTime').combobox('getData');
				$("#comboxExecutionCycleTime").combobox('setValue',cycleTimeData[4].valueCode);
		    }
		    
		});
		
		$('#txtExecutionCycleNumber').bind('input propertychange', function() {
			var chooseVal = $("#comboxExecutionCycleTime").combobox('getValue');
			var cycleNum = $('#txtExecutionCycleNumber').val();
	    	if(chooseVal == "5" && cycleNum == "1")
			{
				$(".daySel").show();
			}else{
				$(".daySel").hide();
			}
		});
		
		
		$('#txtStartTime').datetimebox('setValue', Date.parse(new Date()).toString());
		setTimeout(function(){
			$("#txtStartTime").siblings(".textbox").children(".textbox-text").val($("#txtStartTime").combobox('getText'));
		},50);
		
		$('#txtEndTime').datetimebox('setValue', '2020-01-01 00:00:00');
		setTimeout(function(){
			$("#txtEndTime").siblings(".textbox").children(".textbox-text").val($("#txtEndTime").combobox('getText'));
		},50);
		  
		
		
		//源主机所属领域
		$("#sourceFieldSet_1 .sourceComboxFieldName").combobox({
			url: BASE_URL_FIELD_SEARCH + '/findAllFields' + '?v=' + Math.random(),
			valueField: 'id',
		    textField: 'name',
		    editable:false,
		    method:'get',
		    loadFilter: function(data){
		    	return data.content;
		    },
		    onLoadSuccess:function(){
		    	var FieldName = $("#sourceFieldSet_1 .sourceComboxFieldName").combobox('getData');
		    	$("#sourceFieldSet_1 .sourceComboxFieldName").combobox('setValue',FieldName[0].id);
		    },	
		    onSelect: function(record){
		    	sourceComboxSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: record.id},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findFieldSystemsByField' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
        		    loadFilter: function(data){
        		    	return data.content;
        		    }
                }).load();
		    },
		    onChange: function(newValue,oldValue){
		    	sourceComboxSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: newValue},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findFieldSystemsByField' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
        		    loadFilter: function(data){
        		    	return data.content;
        		    },
        		    onLoadSuccess : function(){
        		    	var SystemName = $("#sourceFieldSet_1 .sourceComboxSystemName").combobox('getData');
        		    	$("#sourceFieldSet_1 .sourceComboxSystemName").combobox('setValue',SystemName[0].id);
        		    }
                }).load();
		    }
		    
		});
		
		//源主机所属系统
		var sourceComboxSystemName = $("#sourceFieldSet_1 .sourceComboxSystemName").combobox({
            disabled: true,
            valueField: 'id',
            textField: 'name',
            editable:false
        });
		
		
		//目标主机所属领域
		$("#desFieldSet_1 .desComboxFieldName").combobox({
			url: BASE_URL_FIELD_SEARCH + '/findAllFields' + '?v=' + Math.random(),
			valueField: 'id',
		    textField: 'name',
		    editable:false,
		    method:'get',
		    loadFilter: function(data){
		    	return data.content;
		    },
		    onLoadSuccess:function(){
		    	var FieldName = $("#desFieldSet_1 .desComboxFieldName").combobox('getData');
		    	$("#desFieldSet_1 .desComboxFieldName").combobox('setValue',FieldName[0].id);
		    },	
		    onSelect: function(record){
		    	desComboxSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: record.id},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findFieldSystemsByField' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
        		    loadFilter: function(data){
        		    	return data.content;
        		    }
                }).load();
		    },
		    onChange: function(newValue,oldValue){
		    	desComboxSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: newValue},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findFieldSystemsByField' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
        		    loadFilter: function(data){
        		    	return data.content;
        		    },
        		    onLoadSuccess : function(){
        		    	var SystemName = $("#desFieldSet_1 .desComboxSystemName").combobox('getData');
        		    	$("#desFieldSet_1 .desComboxSystemName").combobox('setValue',SystemName[0].id);
        		    }
                }).load();
		    }
		    
		});
		
		
		//目标主机所属系统
		var desComboxSystemName = $("#desFieldSet_1 .desComboxSystemName").combobox({
            disabled: true,
            valueField: 'id',
            textField: 'name',
            editable:false
        });
	  	function onLeaveStepCallBack(obj, context){
	  		isFtpTest = false;
	  		var step_num= obj.attr('rel'); // get the current step number
	  		/*验证表单数据是否正确*/
	  		//alert("Leaving step " + context.fromStep + " to go to step " + context.toStep);
	  		if(context.fromStep < context.toStep){
		  		if(step_num == 1){
		  			if(!$("#basicInfoForm").form("validate")){
		  				return false;
		  			}
		  		}else if(step_num == 2){
		  			var sourceDatas = getSourceDatas();
					if(sourceDatas == false){
						return false;
					}
					
		  		}else if(step_num == 3){
		  			var desDatas = getDesDatas();
					if(desDatas == false){
						return false;
					}
		  		}else if(step_num == 4){
		  			/*var packageJarNames = $.trim($("#packageJarName").val());
					if(packageJarNames != "")
					{
					}else
					{
						$.messager.alert('警告', '<p>接口部署包不能为空!</p>', 'warning');
						return false;
					}*/
		  		}else{
		  			
		  		}
	  		}
	  		return true;
	  		
	  	}
	  	
	  	function onShowStepCallBack(obj){
	  		var step_num= obj.attr('rel');
	  		if(step_num == 1){
	  			//alert("onShowStepCallBack" + step_num);
	  		}else if(step_num == 2){
	  			//alert("onShowStepCallBack" + step_num);
	  		}else if(step_num == 3){
	  			//alert("onShowStepCallBack" + step_num);
	  		}else{
	  			//alert("onShowStepCallBack" + step_num);
	  		}
	  		
	  	}
	  	
	  	function onFinishCallBack(){
	  		isFtpTest = false;
	  		var result = getFormDatas();
	  		if(result == false){
	  			return ;
	  		}
	  		var interfaceDatas = getFormDatas();
	  		var jsonData = {
				  	interfaceDatas:interfaceDatas
				};
	  		//alert(JSON.stringify(jsonData));
	  		if($("#basicInfoForm").form("validate")){
	  			$("#progressbar, #progressbar_tips").fadeIn();
	  			loading_point.timer = setInterval(loading,200);
		  		$.ajax({
		  			type: "post",
		  			url: BASE_URL_HTTP_INTERFACE + '/ftpServiceRegister' + '?v=' + Math.random(),
		  			dataType:'json',
		  			data: JSON.stringify(jsonData),
		  			contentType:"application/json",
		  			success: function(result) {
		  				$("#progressbar, #progressbar_tips").fadeOut();
						clearInterval(loading_point.timer);
		  				//alert("result" + result.backValue);
		  				if(result.backValue == true){
		  					$.messager.alert('提示','<p>注册成功</p>','info',function(){
		  						//window.location.href = "businessServiceManagement.html";
		  						window.parent.OpenTab("业务服务管理","pages/esb/ServiceManagement/businessServiceManagement.html","", true);
		  					});
		  				}else if(result.backValue == false){
		  					$.messager.alert('错误','<p>' + result.errorDes + '</p>', 'error');
		  				}
		  			},
		  			error: function() {
		  				$("#progressbar, #progressbar_tips").fadeOut();
						clearInterval(loading_point.timer);
		  				$.messager.alert('错误','<p>服务异常，注册失败，请稍后重试或联系管理员!</p>', 'error');
		  			}
		  		});
	  		}
	  		
	  	}
		
		
		/* 可见范围 */
		$("#selSystemBtn").click(function(e) {
			//if(treeData==null){
				$("#tt").tree({
					url:BASE_URL_TREE + '/getFieldSystemsForEasyUiTree' + '?v=' + Math.random(),
					method: "get",
					lines:false,
					async:false,
					checkbox: true,
					loadFilter: function(data,parent) {
						treeData = [{text:"全部", children:data, nodeType:"root"}];
						return treeData;
					},
					onLoadSuccess:function()
					{
						$("#tt > li > ul > li > ul > li > .tree-node > .tree-file").css("background","url('../../../images/st_folder.png') no-repeat 2px 2px");
						$("#tt > li > ul > li > .tree-node > .tree-file").parent().parent().css("display","none");
						reSetTree();
					},
					onClick:function(node){
						if(node.checked)
						{
							$("#tt").tree("uncheck", node.target);
						}
						else
						{
							$("#tt").tree("check", node.target);
						}
						
						//$("#systemName").val(node.text);
						//choose_tree();
					}
				});
			//}else{
				//reSetTree()
			//}
			
			
			return false;
		});
		
		$("#ensureSelect").click(function (e) {
			var checkedNodes = $("#tt").tree("getChecked");
			var selectSystems = "";
			var systemsName = "";
			for(var i = 0, len = checkedNodes.length; i < len; ++i)
			{
				var tempNode = checkedNodes[i];
				if(tempNode.nodeType != "fieldSystem")
				{
					continue;
				}
				selectSystems += (selectSystems != ""? ",":"") + tempNode.id;
				systemsName += (systemsName != ""? ",":"") + tempNode.text;
			}
			$("#strFieldSystems").val(selectSystems);
			$("#system").val(systemsName);
			$('#system_selection').window('close');	
		});
		
		
		$("#searchNode").click(function (e) { 
			if($("#systemName").val() != '')
			{
				choose_tree();
			}
			else
			{
				$(".systemName").val("");
				var row = $('#tt li .tree-node');  
				row.removeClass('tree-node-selected');
				$(".tree_con").scrollTop(0);
			}
		});
		
		$("#systemName").bind('input propertychange', function() {
			arrayLi = [];
			arrayLiInd = 0;
			if($("#systemName").val() != '')
			{
				choose_tree();
			}else
			{
				$("#ff input").val("");
				var row = $('#tt li .tree-node');  
				row.removeClass('tree-node-selected');
				$(".tree_con").scrollTop(0);
			}
		});
		
		$(document , "#systemName").keyup(function(event){
		  if(event.keyCode == 8){
		    $("#searchNode").trigger("click");
		  }
		});
		$(document , "#systemName").keyup(function(event){
		  if(event.keyCode ==13){
		    $("#searchNode").trigger("click");
		  }
		});
		
		/* 可见范围 */
			
  	}); 
  
	
	//获取所有表单数据
	var interfaceDatas;
	function getFormDatas(){
			var sourceDatas = getSourceDatas();
			if(sourceDatas == false){
				return false;
			}
			var desDatas = getDesDatas();
			if(desDatas == false){
				return false;
			}
		
			var interfaceName = $.trim($("#interfaceName").val());
			var interfaceCode = $("#interfaceCode").val();
			var fieldId = $("#comboxFieldName").combobox("getValue");
			var systemId = $("#comboxSystemName").combobox("getValue");
			var interfaceVersion = $.trim($("#interfaceVserion").val());
			var interfaceDes = $.trim($("#interfaceDescriptions").val());
  			var overTimeSetting = $.trim($("#overTimeSetting").val());
  			var isPublic = $("#comboxIsPublic").combobox("getValue");
  			
  			var runWay = $("#comboxExecutionCycleTime").combobox('getValue');
  			var runCyc = $("#txtExecutionCycleNumber").val();
  			var beginTime = $("#txtStartTime").datetimebox('getValue');
  			var endTime = $("#txtEndTime").datetimebox('getValue');
  			
  			var dayOfWeek = $("input[name='qx']:checked").map(function () {
  	            return $(this).val();
  	        }).get().join(',');
  			
  			var isSchedule = $("#is_schedule").is(":checked");
  			if(isSchedule){
	  			//alert(beginTime);
	  			if(beginTime == null || beginTime == ""){
	  				$.messager.alert('警告', '<p>开始时间不能为空</p>', 'warning');
	  				return false;
	  			}
	  			if(runWay != 1){
	  				if(!comptime(beginTime,endTime)){
	  					$.messager.alert('警告', '<p>结束时间要大于开始时间</p>', 'warning');
	  					return false;
	  				}
	  			}else{
	  				endTime = "";
	  			}
	  			if(runWay != 5){
	  				dayOfWeek = "";
	  			}
  			}
  			
  			/*var fileCachePath = $("#fileCachePath").val();*/
  			
  			interfaceDatas = {
				interfaceName:interfaceName,
	  			interfaceCode:interfaceCode,
	  			fieldId:fieldId,
	  			systemId:systemId,
	  			interfaceVersion:interfaceVersion,
	  			interfaceDes:interfaceDes,
				overTimeSetting:overTimeSetting,
				isPublic:isPublic,
				runWay:runWay,
				runCyc:runCyc,
				dayOfWeek:dayOfWeek,
				beginTime:beginTime,
				endTime:endTime,
				isSchedule:isSchedule,
				/*fileCachePath:fileCachePath,*/
				sourceDatas:sourceDatas,
				desDatas:desDatas
			}
  			
  			var fieldSystemsStr = $("#strFieldSystems").val();
  			if(fieldSystemsStr != ""){
	  			if(fieldSystemsStr.indexOf(",") != -1){
	  				interfaceDatas["fieldSystemIds"] = fieldSystemsStr == ""? []:fieldSystemsStr.split(",");
	  			}else{
	  				interfaceDatas["fieldSystemIds"] = [fieldSystemsStr];
	  			}
  			}else{
  				interfaceDatas["fieldSystemIds"] = [];
  			}
  			
  			
  			//alert(JSON.stringify(interfaceDatas));
  			return interfaceDatas;
	}
	
	
	
	
	
	function setChecked(sysName) {
		if(!sysName)
		{
			return;
		}
		$("#tt li .tree-node").each(function(){
			if($(".tree-title", $(this)).text() == sysName)
			{
				$('#tt').tree('check', this);
				return false;
			}
		});
		
	}
	
	function setCheckedList(sysNameArr)
	{
		if(sysNameArr && sysNameArr.length)
		{
			for(var i = 0, len = sysNameArr.length; i < len; ++i)
			{
				setChecked(sysNameArr[i]);
			}
		}
	}
	
	function reSetTree(){
		$('#system_selection').window('open');	
		var txtInterface = $("#system").val().split(",")[0];
	
		if(txtInterface !== '')
		{
			$("#systemName").val(txtInterface);
			choose_tree();
		}
		else
		{
			$("#systemName").val('');
			$(".tree_con").scrollTop(0);
			var row = $('#tt li .tree-node');  
			row.removeClass('tree-node-selected');
		}
		
		var checkedNodes = $("#tt").tree("getChecked");
		if(checkedNodes)
		{
			$.each(checkedNodes, function(index, node) {
				$("#tt").tree("uncheck", node.target);
			});
		}
		
		var currSystemsStr = $("#system").val();
		if(currSystemsStr != '')
		{
			setCheckedList(currSystemsStr.split(","));
		}
	}
	
	
	function choose_tree()
	{
		$('#tt').tree('expandAll');
		if(arrayLi.length == 0 && arrayLiInd == 0)
		{
			var searchVal = $("#systemName").val().toUpperCase(); 
			var row = $('#tt li .tree-node');  
			var rowcolumn = $('#tt li .tree-node > .tree-title');  
			var i = 0, j = 0;
			var offsetC = 0
			row.removeClass('tree-node-selected');  
			rowcolumn.each(function (column) {  
				var matchVal = $(this).text(); 
				if(matchVal.indexOf(searchVal) != -1)
				{
					i++;
					var panel_top = parseInt($(this).parents(".panel").css("top"), 10);
					
					if(i <= 1)
					{
						$(this).parent().addClass('tree-node-selected'); 
						var top = $(".tree_con").scrollTop() + $(this).offset().top - 76 - panel_top;
						$(".tree_con").scrollTop(top);
						arrayLiInd = 1;
					}			
					arrayLi.push([matchVal,$(".tree_con").scrollTop() + $(this).offset().top - 76 - panel_top]);
					
				}
				}); 
			}else
			{
				var rowcolumn = $('#tt li .tree-node > .tree-title'); 
				var row = $('#tt li .tree-node');  
				row.removeClass('tree-node-selected');
				
				if(arrayLiInd <  arrayLi.length)
				{
					rowcolumn.each(function (column) {  
						var matchVal = $(this).text(); 
						if(matchVal == arrayLi[arrayLiInd][0])
						{
							$(this).parent().addClass('tree-node-selected'); 
							$(".tree_con").scrollTop(arrayLi[arrayLiInd][1]);
							arrayLiInd++;
							return false;
						}
					});
				}else
				{
					//arrayLi = [];
					arrayLiInd = 0;
					$(".tree_con").scrollTop(0);
					choose_tree();
				}
			}
	}
	
	var sourceBegin = 1;
	function addSourceHost(){
		
		var fieldSystemElement = "<ul>"
							  + "<li>"
				              + "<label for=\"sourceComboxFieldName\"  class=\"label\">所属领域：</label>"
				              + "      <div class=\"input_con\">"
				              + "      <input type=\"text\" name=\"sourceComboxFieldName\" class=\"sourceComboxFieldName easyui-combobox text\" tabindex=\"8\"/>"
				              + "      </div>"
				              + "  </li>"
				              + "  <li>"
				              + "      <label for=\"sourceComboxSystemName\"  class=\"label\">所属系统：</label>"
				              + "      <div class=\"input_con\">"
				              + "      <input type=\"text\" name=\"sourceComboxSystemName\" class=\"sourceComboxSystemName easyui-combobox text\" tabindex=\"8\"/>"
				              + "      </div>"
				              + "  </li>"
				              + " </ul>";
		if(desBegin >= 2 && sourceBegin >= 1){
			$.messager.alert('警告', '<p>FTP接口暂不支持多个源对应多个目标的文件传输方式!</p>', 'warning');
			return false;
		}
		var sourceFieldSetVal = '<fieldset id="sourceFieldSet_' + (sourceBegin+1) + '" style="border: 1px solid #ced6db;"><legend style="margin-left: 10px;">源_' +　(sourceBegin+1) +'</legend>' + fieldSystemElement + '<div class="sourceDiv">' + $("#sourceFieldSet_" + sourceBegin + " .sourceDiv").html() + "</div></fieldset>";
		$("#sourceFieldSet_" + sourceBegin).after(sourceFieldSetVal);
		var isAnomous = $("#sourceFieldSet_" + sourceBegin + " .sourceAnmous").is(":checked");
		if(isAnomous){
			$(this).parent().siblings(".sourceUserInfo").css("display", "none");
			$("#sourceFieldSet_" + (sourceBegin+1) + " .sourceAnmous").attr('checked','checked');
		}else{
			$(this).parent().siblings(".sourceUserInfo").css("display", "block");
			$("#sourceFieldSet_" + (sourceBegin+1) + " .sourceAnmous").removeAttr('checked');
		}
		
		sourceBegin = sourceBegin + 1;
		if(sourceBegin > 1){
			$('#toolbarSource_del').linkbutton('enable');
		}else{
			$('#toolbarSource_del').linkbutton('disable');
		}
		//源主机所属领域
		$("#sourceFieldSet_" + (sourceBegin) +  " .sourceComboxFieldName").combobox({
			url: BASE_URL_FIELD_SEARCH + '/findAllFields' + '?v=' + Math.random(),
			valueField: 'id',
		    textField: 'name',
		    editable:false,
		    method:'get',
		    loadFilter: function(data){
		    	return data.content;
		    },
		    onLoadSuccess:function(){
		    	var FieldName = $("#sourceFieldSet_" + (sourceBegin) +  " .sourceComboxFieldName").combobox('getData');
		    	$("#sourceFieldSet_" + (sourceBegin) +  " .sourceComboxFieldName").combobox('setValue',FieldName[0].id);
		    },	
		    onSelect: function(record){
		    	sourceComboxSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: record.id},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findFieldSystemsByField' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
        		    loadFilter: function(data){
        		    	return data.content;
        		    }
                }).load();
		    },
		    onChange: function(newValue,oldValue){
		    	sourceComboxSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: newValue},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findFieldSystemsByField' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
        		    loadFilter: function(data){
        		    	return data.content;
        		    },
        		    onLoadSuccess : function(){
        		    	var SystemName = $("#sourceFieldSet_" + (sourceBegin) +  " .sourceComboxSystemName").combobox('getData');
        		    	$("#sourceFieldSet_" + (sourceBegin) +  " .sourceComboxSystemName").combobox('setValue',SystemName[0].id);
        		    }
                }).load();
		    }
		    
		});
		
		//源主机所属系统
		var sourceComboxSystemName = $("#sourceFieldSet_" + (sourceBegin) +  " .sourceComboxSystemName").combobox({
            disabled: true,
            valueField: 'id',
            textField: 'name',
            editable:false
        });
	}
	
	function deleteSourceHost(){
		if(sourceBegin > 1){
			$("#sourceFieldSet_" + sourceBegin).remove();
			sourceBegin = sourceBegin - 1;
			if(sourceBegin == 1){
				$('#toolbarSource_del').linkbutton('disable');
			}
		}else{
			
		}
	}
	
	
	var desBegin = 1;
	function addDesHost(){
		
		var fieldSystemElement = "<ul>"
			  + "<li>"
            + "<label for=\"desComboxFieldName\"  class=\"label\">所属领域：</label>"
            + "      <div class=\"input_con\">"
            + "      <input type=\"text\" name=\"desComboxFieldName\" class=\"desComboxFieldName easyui-combobox text\" tabindex=\"8\"/>"
            + "      </div>"
            + "  </li>"
            + "  <li>"
            + "      <label for=\"desComboxSystemName\"  class=\"label\">所属系统：</label>"
            + "      <div class=\"input_con\">"
            + "      <input type=\"text\" name=\"desComboxSystemName\" class=\"desComboxSystemName easyui-combobox text\" tabindex=\"8\"/>"
            + "      </div>"
            + "  </li>"
            + " </ul>"
            
            
		if(sourceBegin >= 2 && desBegin >= 1){
			$.messager.alert('警告', '<p>FTP接口暂不支持多个源对应多个目标的文件传输方式!</p>', 'warning');
			return false;
		}
		var desFieldSetVal = '<fieldset id="desFieldSet_' + (desBegin+1) + '" style="border: 1px solid #ced6db;"><legend style="margin-left: 10px;">目标_' +　(desBegin+1) +'</legend>' + fieldSystemElement + '<div class="desDiv">' + $("#desFieldSet_" + desBegin + " .desDiv").html() + "</div></fieldset>";
		$("#desFieldSet_" + desBegin).after(desFieldSetVal);
		var isAnomous = $("#desFieldSet_" + desBegin + " .desAnmous").is(":checked");
		if(isAnomous){
			$(this).parent().siblings(".desUserInfo").css("display", "none");
			$("#desFieldSet_" + (desBegin+1) + " .desAnmous").attr('checked','checked');
		}else{
			$(this).parent().siblings(".desUserInfo").css("display", "block");
			$("#desFieldSet_" + (desBegin+1) + " .desAnmous").removeAttr('checked');
		}
		
		desBegin = desBegin + 1;
		if(desBegin > 1){
			$('#toolbarDes_del').linkbutton('enable');
		}else{
			$('#toolbarDes_del').linkbutton('disable');
		}
		//目标主机所属领域
		$("#desFieldSet_" + (desBegin) + " .desComboxFieldName").combobox({
			url: BASE_URL_FIELD_SEARCH + '/findAllFields' + '?v=' + Math.random(),
			valueField: 'id',
		    textField: 'name',
		    editable:false,
		    method:'get',
		    loadFilter: function(data){
		    	return data.content;
		    },
		    onLoadSuccess:function(){
		    	var FieldName = $("#desFieldSet_" + (desBegin) + " .desComboxFieldName").combobox('getData');
		    	$("#desFieldSet_" + (desBegin) + " .desComboxFieldName").combobox('setValue',FieldName[0].id);
		    },	
		    onSelect: function(record){
		    	desComboxSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: record.id},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findFieldSystemsByField' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
        		    loadFilter: function(data){
        		    	return data.content;
        		    }
                }).load();
		    },
		    onChange: function(newValue,oldValue){
		    	desComboxSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: newValue},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findFieldSystemsByField' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
        		    loadFilter: function(data){
        		    	return data.content;
        		    },
        		    onLoadSuccess : function(){
        		    	var SystemName = $("#desFieldSet_" + (desBegin) + " .desComboxSystemName").combobox('getData');
        		    	$("#desFieldSet_" + (desBegin) + " .desComboxSystemName").combobox('setValue',SystemName[0].id);
        		    }
                }).load();
		    }
		    
		});
		
		
		//目标主机所属系统
		var desComboxSystemName = $("#desFieldSet_" + (desBegin) + " .desComboxSystemName").combobox({
            disabled: true,
            valueField: 'id',
            textField: 'name',
            editable:false
        });
		
	}
	
	function deleteDesHost(){
		if(desBegin > 1){
			$("#desFieldSet_" + desBegin).remove();
			desBegin = desBegin - 1;
			if(desBegin == 1){
				$('#toolbarDes_del').linkbutton('disable');
			}
		}else{
			
		}
	}
	
	
	
	$("#sourceHostForm").delegate(".sourceAnmous","change", function(){
		var chooseVal = $(this).is(":checked");
		if(chooseVal){
			$(this).parent().siblings(".sourceUserInfo").css("display", "none");
			//$(".sourceUserInfo").css("display", "none");
		}else{
			$(this).parent().siblings(".sourceUserInfo").css("display", "block");
		}
	});
	
	$("#desHostForm").delegate(".desAnmous","change", function(){
		var chooseVal = $(this).is(":checked");
		if(chooseVal){
			$(this).parent().siblings(".desUserInfo").css("display", "none");
		}else{
			$(this).parent().siblings(".desUserInfo").css("display", "block");
		}
	});
	//IP地址验证
	var regIP = /^((1?\d?\d|(2([0-4]\d|5[0-5])))\.){3}(1?\d?\d|(2([0-4]\d|5[0-5])))$/;
	
	var regDomain = /^[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+.?$/;
	//端口验证
	var parten = /^(\d)+$/g;
	function getSourceDatas(){
		var sourceDatas = [];
		var sourceObject = {};
		
		for(var i = 1; i <=　sourceBegin; i++){
			
			var fieldSystemId = $("#sourceFieldSet_" + i + " .sourceComboxSystemName").combobox('getValue');
			var sourceHost = $("#sourceFieldSet_" + i + " .sourceHost").val();
			if(sourceHost != "")
			{
//				if(regIP.test(sourceHost)) {
//					
//				}else{
//					$.messager.alert('警告', '<p>源主机ip地址格式不正确，请输入正确ip地址格式如：127.0.0.1 !</p>', 'warning');
//					return false;
//				}
				
			}else
			{
				$.messager.alert('警告', '<p>源主机不能为空!</p>', 'warning');
				return false;
			}
			
			var sourceHostPort = $("#sourceFieldSet_" + i + " .sourceHostPort").val();
			if(sourceHostPort != "")
			{
				if(parten.test(sourceHostPort)==true && (parseInt(sourceHostPort) <= 65535)==true && (parseInt(sourceHostPort) >= 0)==true){
				}else{
					$.messager.alert('警告', '<p>源主机端口格式不正确，请输入正确格式的端口号（0~65535）!</p>', 'warning');
					return false;
				}
				parten.lastIndex = 0;
			}else
			{
				$.messager.alert('警告', '<p>源主机端口不能为空，请输入正确格式的端口号（0~65535）!</p>', 'warning');
				return false;
			}
			var sourceIsAnmous = $("#sourceFieldSet_" + i + " .sourceAnmous").is(":checked");
			var sourceUserName = $("#sourceFieldSet_" + i + " .sourceUserName").val();
			var sourcePassword = $("#sourceFieldSet_" + i + " .sourcePassword").val();
			if(!sourceIsAnmous){
				if(sourceUserName != "")
				{
					if(sourceUserName.length > 50){
						$.messager.alert('警告', '<p>源用户名必须少于50个字符!</p>', 'warning');
						return false;
					}
				}else
				{
					$.messager.alert('警告', '<p>源用户名不能为空!</p>', 'warning');
					return false;
				}
				
				if(sourcePassword != "")
				{
					if(sourcePassword.length > 50){
						$.messager.alert('警告', '<p>源密码必须少于50个字符!</p>', 'warning');
						return false;
					}
				}else
				{
					$.messager.alert('警告', '<p>源密码不能为空!</p>', 'warning');
					return false;
				}
			}
			var sourceFilePath = $("#sourceFieldSet_" + i + " .sourceFilePath").val();
			var sourceFtpServerCode = $("#sourceFieldSet_" + i + " .sourceFtpServerCode option:selected").val();
			var sourceIsDelFile = $("#sourceFieldSet_" + i + " .sourceFileDelete").is(":checked");
			var sourcePassiveMode = $("#sourceFieldSet_" + i + " .sourcePassiveMode").is(":checked");
			var matchMode = $("#sourceFieldSet_" + i + " .matchMode option:selected").val();
			var sourceFileName = $("#sourceFieldSet_" + i + " .sourceFileName").val();
			if(isFtpTest){
				
			}else{
				if(sourceFileName != "")
				{
					if(sourceFileName.length > 50){
						$.messager.alert('警告', '<p>文件名称必须少于50个字符!</p>', 'warning');
						return false;
					}
				}/*else
				{
					$.messager.alert('警告', '<p>文件名称不能为空!</p>', 'warning');
					return false;
				}*/
			}
			var hostType = "1";
			sourceObject = {
					fieldSystemId:fieldSystemId,
					sourceHost:sourceHost,
					sourceHostPort:sourceHostPort,
					sourceIsAnmous:sourceIsAnmous,
					sourceUserName:sourceUserName,
					sourcePassword:sourcePassword,
					sourceFilePath:sourceFilePath,
					sourceIsDelFile:sourceIsDelFile,
					sourcePassiveMode:sourcePassiveMode,
					matchMode:matchMode,
					sourceFileName:sourceFileName,
					sourceFtpServerCode:sourceFtpServerCode,
					hostType:hostType
			}
			sourceDatas.push(sourceObject);
			//alert(JSON.stringify(sourceDatas));
		}
		
		return sourceDatas;
	}
	
	
	function getDesDatas(){
		var desDatas = [];
		var desObject = {};
		for(var j = 1; j <=　desBegin; j++){
			var fieldSystemId = $("#desFieldSet_" + j + " .desComboxSystemName").combobox('getValue');
			var desHost = $("#desFieldSet_" + j + " .desHost").val();
			if(desHost != "")
			{
//				if(regIP.test(desHost)) {
//					
//				}else{
//					$.messager.alert('警告', '<p>目标主机ip地址格式不正确，请输入正确ip地址格式如：127.0.0.1 !</p>', 'warning');
//					return false;
//				}
			}else
			{
				$.messager.alert('警告', '<p>目标主机不能为空!</p>', 'warning');
				return false;
			}
			var desHostPort = $("#desFieldSet_" + j + " .desHostPort").val();
			if(desHostPort != "")
			{
				if(parten.test(desHostPort) && parseInt(desHostPort) <= 65535&& parseInt(desHostPort) >= 0){
					
				}else{
					$.messager.alert('警告', '<p>目标主机端口格式不正确，请输入正确格式的端口号（0~65535）!</p>', 'warning');
					return false;
				}
				parten.lastIndex = 0;
			}else
			{
				$.messager.alert('警告', '<p>目标主机端口不能为空，请输入正确格式的端口号（0~65535）!</p>', 'warning');
				return false;
			}
			var desIsAnmous = $("#desFieldSet_" + j + " .desAnmous").is(":checked");
			var desUserName = $("#desFieldSet_" + j + " .desUserName").val();
			var desPassword = $("#desFieldSet_" + j + " .desPassword").val();
			if(!desIsAnmous){
				if(desUserName != "")
				{
					if(desUserName.length > 50){
						$.messager.alert('警告', '<p>目标用户名必须少于50个字符!</p>', 'warning');
						return false;
					}
				}else
				{
					$.messager.alert('警告', '<p>目标用户名不能为空!</p>', 'warning');
					return false;
				}
				
				if(desPassword != "")
				{
					if(desPassword.length > 50){
						$.messager.alert('警告', '<p>目标密码必须少于50个字符!</p>', 'warning');
						return false;
					}
				}else
				{
					$.messager.alert('警告', '<p>目标密码不能为空!</p>', 'warning');
					return false;
				}
			}
			var desFilePath = $("#desFieldSet_" + j + " .desFilePath").val();
			var desIsCoverFile = $("#desFieldSet_" + j + " .desFileCover").is(":checked");
			var desPassiveMode = $("#desFieldSet_" + j + " .desPassiveMode").is(":checked");
			
			var desFtpServerCode = $("#desFieldSet_" + j + " .desFtpServerCode option:selected").val();
			
			var hostType = "2";
			desObject = {
					fieldSystemId:fieldSystemId,
					desHost:desHost,
					desHostPort:desHostPort,
					desIsAnmous:desIsAnmous,
					desUserName:desUserName,
					desPassword:desPassword,
					desFilePath:desFilePath,
					desIsCoverFile:desIsCoverFile,
					desPassiveMode:desPassiveMode,
					desFtpServerCode:desFtpServerCode,
					hostType:hostType
			}
			desDatas.push(desObject);
		}
		
		return desDatas;
	}
	
	
	// 测试源ftp服务器是否可连接
	function testSourceFtpServer(){
		isFtpTest = true;
		var sourceDatas =  getSourceDatas();
		if(sourceDatas == false){
			return false;
		}
		var jsonData = {
			hostDatas:sourceDatas
		};
		$("#progressbar, #progressbar_tips").fadeIn();
		loading_point.timer = setInterval(loading,200);
	  	$.ajax({
	  		type: "post",
	  		url: BASE_URL_HTTP_INTERFACE + '/testFtpServer' + '?v=' + Math.random(),
	  		dataType:'json',
	  		data: JSON.stringify(jsonData),
	  		contentType:"application/json",
	  		success: function(result) {
	  			$("#progressbar, #progressbar_tips").fadeOut();
				clearInterval(loading_point.timer);
	  			if(result.backValue == true){
	  				$.messager.alert('提示','<p>测试成功!</p>', 'info');
	  			}else if(result.backValue == false){
	  				$.messager.alert('错误','<p>' + result.errorDes + '!</p>', 'error');
	  			}	
	  		},
	  		error: function() {
	  			$("#progressbar, #progressbar_tips").fadeOut();
				clearInterval(loading_point.timer);
	  			$.messager.alert('错误','<p>服务异常，测试失败，请稍后重试或联系管理员!</p>', 'error');
	  		}
	  	});
	}
	
	//测试目标ftp服务器是否可连接
	function testDesFtpServer(){
		var desDatas =  getDesDatas();
		if(desDatas == false){
			return false;
		}
		
		var jsonData = {
			hostDatas:desDatas
		};
		$("#progressbar, #progressbar_tips").fadeIn();
		loading_point.timer = setInterval(loading,200);
	  	$.ajax({
	  		type: "post",
	  		url: BASE_URL_HTTP_INTERFACE + '/testFtpServer' + '?v=' + Math.random(),
	  		dataType:'json',
	  		data: JSON.stringify(jsonData),
	  		contentType:"application/json",
	  		success: function(result) {
	  			$("#progressbar, #progressbar_tips").fadeOut();
				clearInterval(loading_point.timer);
	  			if(result.backValue == true){
	  				$.messager.alert('提示','<p>测试成功!</p>', 'info');
	  			}else if(result.backValue == false){
	  				$.messager.alert('错误','<p>' + result.errorDes + '!</p>', 'error');
	  			}	
	  		},
	  		error: function() {
	  			$("#progressbar, #progressbar_tips").fadeOut();
				clearInterval(loading_point.timer);
	  			$.messager.alert('错误','<p>服务异常，测试失败，请稍后重试或联系管理员!</p>', 'error');
	  		}
	  	});
	}
	
	
	$("#is_schedule").change(function(){
		var chooseVal = $("#is_schedule").is(":checked");
		if(chooseVal){
			$(".sheduleTrigger").show();
			$(".externalTrigger").hide();
		}else{
			var interfaceCode = $("#interfaceCode").val();
			var systemId = $("#comboxSystemName").combobox("getValue");
			var interfaceVersion = $.trim($("#interfaceVserion").val());
			
			$.ajax({
		  		type: "get",
		  		url: BASE_URL_HTTP_INTERFACE + '/getRequestAddress' + '?interfaceCode=' + interfaceCode + '&systemId=' + systemId + '&interfaceVersion=' + interfaceVersion + '&v=' + Math.random(),
		  		dataType:'json',
		  		contentType:"application/json",
		  		success: function(result) {
		  			$("#requestTriggerAddress").val(result.routePublishUrl);
		  		},
		  		error: function() {
		  			$.messager.alert('错误','<p>服务异常，获取调用地址失败，请稍后重试或联系管理员!</p>', 'error');
		  		}
		  	});
			$(".sheduleTrigger").hide();
			$(".externalTrigger").show();
		}
	});
	
	
	var loading_point = {
			timer:null,
			len:3,
			count:0
		};
	function loading()
	{
	 	if(loading_point.count < loading_point.len)
		{
			loading_point.count++;
			$("#progressbar_point").text($("#progressbar_point").text() + ".");
		}else
		{
			loading_point.count = 0;
			$("#progressbar_point").text("");
		}	
	}
	
	
	